<?php

//define default wsdl url;

define("OAUTH_DEFAULT_WSDL_URL", "http://40.49.64.8:8088/sapsso/services/SSOService?wsdl");
//define default cookie name;
define("OAUTH_DEFAULT_COOKIE_NAME", "MYSAPSSO2");
//define defualt login url, unauthorized request will be redirected to this url.
define("OAUTH_DEFAULT_LOGIN_URL", "http://");
//define defualt query name of return path.
define("OAUTH_DEFAULT_RETURN_PATH", "from");

/**
 * OAuth
 */
class OAuth {

    static $CACHE_SESSION_KEY = "class.oauth.cache";
    static $CACHE_SESSION_KEY_COOKIE = "class.oauth.cache.cookievalue";
    static $BAD_COOKIE_RECORDS = "bad_cookie_records"; //统计每一个cookie 失败访问的次数, 超过$BAD_COOKIE_RETRY_TIMES次数就放弃访问oa服务器了
    static $BAD_COOKIE_RETRY_TIMES = 2;
    private $wsdlUrl;
    private $cookieName;
    private $_current_cookievalue;
    private $_last_cookievalue = "";

    /**
     *
     * @param string $wsdlUrl The wsdl url, could be started with http://..
     * @param string $cookieName
     */
    public function __construct($wsdlUrl=OAUTH_DEFAULT_WSDL_URL, $cookieName=OAUTH_DEFAULT_COOKIE_NAME) {
        $this->wsdlUrl = $wsdlUrl;
        $this->cookieName = $cookieName;
    }

    public function init($token) {
        //
       // @session_destroy();
        @session_start();
       // print_r($_SESSION);
        if (!isset($_SESSION[OAuth::$BAD_COOKIE_RECORDS])) {
            $_SESSION[OAuth::$BAD_COOKIE_RECORDS] = array();
        }

        //     $_SESSION[OAuth::$CACHE_SESSION_KEY] = "shoaly";
          //   $_SESSION[OAuth::$CACHE_SESSION_KEY_COOKIE] = "cookiet3333333hree13";

        if (!isset($_SESSION[OAuth::$BAD_COOKIE_RECORDS][$token])) {
            $_SESSION[OAuth::$BAD_COOKIE_RECORDS][$token] = 0;
        }




        //unset($_SESSION[OAuth::$CACHE_SESSION_KEY]);
        //$_SESSION[OAuth::$CACHE_SESSION_KEY]="";
    }

    public function verify2($token=null, $useCache=false) {

        $this->init($token);

        if ($_SESSION[OAuth::$BAD_COOKIE_RECORDS][$token] >= OAuth::$BAD_COOKIE_RETRY_TIMES) {

            return null;
        }

        if ($useCache) {
            if (isset($_SESSION[OAuth::$CACHE_SESSION_KEY]) && !empty($_SESSION[OAuth::$CACHE_SESSION_KEY])) {

                if (isset($_SESSION[OAuth::$CACHE_SESSION_KEY_COOKIE]) && $_SESSION[OAuth::$CACHE_SESSION_KEY_COOKIE] == $token) {
                    return $_SESSION[OAuth::$CACHE_SESSION_KEY];
                }
            }
        } else {
            unset($_SESSION[OAuth::$CACHE_SESSION_KEY]);
        }

      //  echo("oa 请求");
        $soapClient = new SoapClient($this->wsdlUrl);
        $response = $soapClient->getUser(array("in0" => $token, "in1" => null));
        $userName = null;

        $flag = false;

        if ($response != null && $response->out != null) { //服务器请求正常返回
            list($userName, $userIp) = split(":", $response->out);
            if (!empty($userName)) {
                $_SESSION[OAuth::$CACHE_SESSION_KEY] = $userName;
                $_SESSION[OAuth::$CACHE_SESSION_KEY_COOKIE] = $token;

                $_SESSION[OAuth::$BAD_COOKIE_RECORDS][$token] = 0;
                $flag = true;
            }
        }
        if (!$flag) {             //如果读取失败,那么给该token添加一次失败的访问标记
            $_SESSION[OAuth::$BAD_COOKIE_RECORDS][$token]++;

        }
        return $userName;
    }

    /**
     *
     * @param string $token userToken.
     * @param boolean $useCache If set true, will check the Session first. If set false, will request OA server every time.
     * @return string Returns userName if token valid, or return null.
     */
    public function verify($token=null, $useCache=false) {
        @session_start();
        if ($useCache) {
            if (isset($_SESSION[OAuth::$CACHE_SESSION_KEY]) && !empty($_SESSION[OAuth::$CACHE_SESSION_KEY]) && $this->_current_cookievalue == $this->_last_cookievalue) {
                return $userName;
            }
        } else {
            unset($_SESSION[OAuth::$CACHE_SESSION_KEY]);
        }

//        if(!isset($bad_cookie_records[$token])){
//            $bad_cookie_records[$token]=0;
//            print_r($bad_cookie_records);
//        }else if($bad_cookie_records[$token]>=$BAD_COOKIE_RETRY_TIMES){ //如果该cookie曾2次都没有拿到值, 那么放弃尝试
//            return "放弃取值";
//        }
        if (!isset(OAuth::$bad_cookie_records[$token])) {
            OAuth::$bad_cookie_records[$token] = 0;
            print_r(OAuth::$bad_cookie_records);
        } else if (OAuth::$bad_cookie_records[$token] >= OAuth::$BAD_COOKIE_RETRY_TIMES) { //如果该cookie曾2次都没有拿到值, 那么放弃尝试
            return "放弃取值";
        }




        $soapClient = new SoapClient($this->wsdlUrl);
        $response = $soapClient->getUser(array("in0" => $token, "in1" => null));
        $userName = null;
        if ($response != null && $response->out != null) { //服务器请求正常返回
            list($userName, $userIp) = split(":", $response->out);
            if (!empty($userName)) {

                $_SESSION[OAuth::$CACHE_SESSION_KEY] = $userName;
                $this->_last_cookievalue = $this->$token;
                $bad_cookie_records[$token] = 0; //从OA那正常的拿到值, 重置该cookie的失败读取次数
                return $userName;
            }
        }

        OAuth::$bad_cookie_records[$token]++; //没有从oa那边拿到值cookie 标记次数+1
        return null;
    }

    /**
     *
     * @param boolean $useCache If set true, will check the Session first. If set false, will request OA server every time.
     * @return string Returns userName if token valid, or return null.
     */
    public function verifyCookie($useCache=false) {
        if (isset($_COOKIE[$this->cookieName])) {
            $userToken = $_COOKIE[$this->cookieName];
            //$this->_current_cookievalue = $userToken; //缓存当前用户的cookie => sessionId,有可能是过期的id这里无法判断
            return $this->verify2($userToken, $useCache);
        }
        return null;
    }

    /**
     *
     * @param boolean $useCache If set true, will check the Session first. If set false, will request OA server every time.
     * @param string $url If unauthorized, request will redirect to this $url?$qName=$returnPath
     * @param string $qName If unauthorized, request will redirect to this $url?$qName=$returnPath
     * @param string $returnPath If unauthorized, request will redirect to this $url?$qName=$returnPath
     * @return string Returns userName if token valid, or redirect to this $url?$qName=$returnPath.
     */
    public static function check($useCache=false, $url=OAUTH_DEFAULT_LOGIN_URL, $qName=OAUTH_DEFAULT_RETURN_PATH, $returnPath=null) {
        $oauth = new OAuth();
        $userName = $oauth->verifyCookie($useCache);
        if (!empty($userName)) {
            return $userName;
        } else {
            if (empty($returnPath)) {
                $returnPath = urlencode("http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
            }
            echo "<script type='text/javascript'>window.location='$url?$qName=$returnPath';</script>";
        }
    }

    /**
     *
     * @return string Returns userName if existed, or returns null;
     */
    public static function currentUser($useCache) {
        // $_COOKIE[$this->cookieName]="cookie";
        //setcookie(OAUTH_DEFAULT_COOKIE_NAME, "cookiet3333333hree");

        $oauth = new OAuth();
        return $oauth->verifyCookie($useCache);
    }

}


?>
